<template>
  <van-form @submit="onSubmit">
    <van-field
      v-model="login.username"
      autocomplete="off"
      name="username"
      label="用户名"
      placeholder="用户名"
      :rules="[{ required: true, message: '用户名不能为空' }]"
    />
    <van-field
      v-model="login.password"
      :type="type"
      :right-icon="type == 'password' ? 'closed-eye' : 'eye-o'"
      @click-right-icon="changeType"
      name="password"
      label="密码"
      placeholder="密码"
      :rules="[{ required: true, message: '密码不能为空' }]"
    />
    <div style="margin: 16px">
      <van-button round block type="info" native-type="submit">提交</van-button>
    </div>
  </van-form>
</template>
<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'passLogin',
  data () {
    return {
      type: 'password',
      login: {
        username: this.$route.query.username
      }
    }
  },
  methods: {
    ...mapMutations('login', ['changeUsername', 'resetUserInfo']),
    changeType () {
      this.type = this.type == 'password' ? 'text' : 'password'
    },
    onSubmit (value) {
      this.$ajax.login(value).then((res) => {
        if (res.code == 200) {
          this.$nextTick(() => {
            this.changeUsername(value.username)
            this.resetUserInfo()

            // localStorage
            // localStorage.setItem("username", value.username);
            // localStorage.setItem("server_token", res.token);

            // sessionStorage
            window.sessionStorage.setItem('username', value.username)
            window.sessionStorage.setItem('server_token', res.token)

            this.$router.push({ name: 'center' })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.van-button--info {
  margin-top: 40px;
  background-color: #ff5f16;
  border-color: #ff5f16;
}
</style>
